﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EzDesk.Apps.Interface.Staff;
using EzDesk.Apps.Model.Staff;
using EzDesk.Apps.ServiceImpl.Attendance.Repositories;
using EzDesk.Apps.ServiceImpl.Attendance.Repositories.Interface;
using EzDesk.Apps.ServiceImpl.Staff.Repositories;
using EzDesk.Apps.ServiceImpl.Staff.Repositories.Interface;
using EzDesk.Core.Model;
using EzDesk.EzAppApi.Utility;
using EzDesk.Utility;
using EzDesk.Utility.Generic;
using EzDesk.Utility.Json;
using EzDesk.Utility.Log;
using EzDesk.Utility.ServiceStatusInfo;
using Microsoft.Practices.Unity;

namespace EzDesk.Apps.ServiceImpl.Staff
{
    public class StaffService : ContainerAccessorBase, IStaffService
    {
        private const string FeedTemplateStr_staff_contractInfoUpdated = "staff_contractInfoUpdated";


        #region [ private methods ]
        public void sendContractInfoUpdatedFeed(Guid senderId, ContactInfo oldContactInfo, ContactInfo newContactInfo)
        {
            // 如果没改 就不发feed
            var isDirty = false;
            var isFirst = true;

            var updateInfoBuilder = new StringBuilder();
            if(!string.IsNullOrEmpty(newContactInfo.MobileNo) && newContactInfo.MobileNo != oldContactInfo.MobileNo)
            {
                updateInfoBuilder.Append("手机号更新为：" + newContactInfo.MobileNo);
                isFirst = false;
                isDirty = true;
            }
            if(!string.IsNullOrEmpty(newContactInfo.QqNumber) && newContactInfo.QqNumber != oldContactInfo.QqNumber)
            {
                if (!isFirst)
                {
                    updateInfoBuilder.Append("<ez:br />");
                }
                updateInfoBuilder.Append("QQ号更新为：" + newContactInfo.QqNumber);
                isDirty = true;
                isFirst = false;
            }
            if(!string.IsNullOrEmpty(newContactInfo.MainEmail) && newContactInfo.MainEmail != oldContactInfo.MainEmail)
            {
                if (!isFirst)
                {
                    updateInfoBuilder.Append("<ez:br />");
                }
                updateInfoBuilder.Append("E-Mail更新为：" + newContactInfo.MainEmail);
                isDirty = true;
                isFirst = false;
            }

            if (!isDirty) return;

            var senderUser = _ezApiClient.GetSimpleUserById(senderId);
            var feedData = new Dictionary<string, string>
                               {
                                   {"senderId", senderId.ToString()},
                                   {"senderName", senderUser.Name},
                                   {"updateInfo", updateInfoBuilder.ToString()},
                               };

            // 发送目标为所有所有人
            var memberString = "everyone";

            var feedId = _ezApiClient.SendFeed(
                FeedTemplateStr_staff_contractInfoUpdated,
                JsonHelper.ConvertToJson(feedData),
                memberString,
                senderId
                );
        }

        #endregion


        private IEzApiClient _ezApiClient
        {
            get { return EzApiClient.Instance; }
        }
        private IContactInfoRepository _staffInfoRepository;

        #region [ Constructors ]
        public StaffService()
        {
            LogEx.TRACE("AttendanceService", "初始化AttendanceService");
            this._staffInfoRepository = Container.Resolve<IContactInfoRepository>();
        }


        public StaffService(
            IEzApiClient ezApiClient,
            IContactInfoRepository staffInfoRepository
            )
        {
            _staffInfoRepository = staffInfoRepository;
        }
        #endregion

        #region [ private methods ]
        private ContactInfo getStaffInfoByUserId(Guid userId)
        {
            var staffInfo = _staffInfoRepository.GetAll().Where(p => p.UserId == userId).SingleOrDefault();

            return staffInfo;
        }
        #endregion


        public StatusInfo<ContactInfo> GetContactInfoByUserId(Guid userId)
        {
            return StatusInfo.Wrap(() => getContactInfoByUserId(userId));
        }

        private ContactInfo getContactInfoByUserId(Guid userId)
        {
            var staffInfo = getStaffInfoByUserId(userId);
            if(staffInfo == null)
            {
                staffInfo = new ContactInfo()
                                {
                                    UserId = userId
                                };
            }

            return staffInfo;

        }

        public StatusInfo<IList<ContactInfo>> GetContactInfos(string memberstring)
        {
            return StatusInfo.Wrap(() =>
            {
                var userList = _ezApiClient.GetAllUsersByMemberString(memberstring);
                return (IList<ContactInfo>)userList.Select(
                    p => getContactInfoByUserId(p.Id))
                    .ToList();
            });
        }


        public StatusInfo UpdateContactInfo(ContactInfo newContactInfo)
        {
            return StatusInfo.Wrap(() =>
            {
                //todo: 判错
                var userId = newContactInfo.UserId;
                var staffInfo = getStaffInfoByUserId(userId);

                if(staffInfo != null)
                {
                    newContactInfo.Id = staffInfo.Id;
                    _staffInfoRepository.Update(newContactInfo, true);
                }
                else
                {
                    staffInfo = new ContactInfo();
                    newContactInfo.Id = Guid.NewGuid();
                    _staffInfoRepository.Add(newContactInfo, true);
                }

                sendContractInfoUpdatedFeed(newContactInfo.UserId, staffInfo, newContactInfo);
            });

        }



        #region [ ContainerAccessorBase Members ]
        protected override IUnityContainer buildContainer()
        {
            return new UnityContainer()
                .RegisterInstance(new EzDeskStaffDataContext())

                .RegisterType<IContactInfoRepository, StaffInfoRepository>();
        }
        #endregion

        public IList<AppFunction> GetExtraAppFunctions(Guid userId, EzDeskUserAgentType userAgent)
        {
            throw new NotImplementedException();
        }



    }
}
